<?php
namespace Api\Controller;
use Common\Util\FFMpeg;
/**
 * 商家朋友圈
 */
class ShopCofController extends ApiController
{
    protected $noCheck = ['lists', 'leave_msg_list', 'segmentupload', 'segmentvideo'];

    function _initialize() {
        parent::_initialize();
    }

    public function lists()
    {
        $type = I('type');
        $shop_id = I('shop_id');
        $page = I('page');
        $size = I('size');

        $where = ['sc.status'=>1];
        if($shop_id){
            $where['sc.shop_id'] = $shop_id;
        }
        $order = "sc.create_time desc";
        $list = [];
        switch ($type) {
            case '1':// 最新
                $list = M('ShopCof')->alias('sc')
                ->join('__SHOP__ s ON sc.shop_id=s.id', 'left')
                ->join('__USER__ u ON sc.user_id=u.id', 'left')
                ->where($where)
                ->order($order)
                ->page($page, $size)
                ->field('sc.*,u.nickname,u.img as avatar,s.shopname')
                ->select();
                break;
            case '2':// 推荐
                // $where['sc.is_recommend'] = 1;
                $order = "sc.like_num desc,sc.create_time desc";
                $list = M('ShopCof')->alias('sc')
                ->join('__SHOP__ s ON sc.shop_id=s.id', 'left')
                ->join('__USER__ u ON sc.user_id=u.id', 'left')
                ->where($where)
                ->where($where)
                ->order($order)
                ->page($page, $size)
                ->field('sc.*,u.nickname,u.img as avatar,s.shopname')
                ->select();
                break;
            case '3':// 附近
                //经度
                $lng = I('lng');
                //纬度
                $lat = I('lat');
                $shop_where = [];
                I('pro') && $shop_where['pro'] = I('pro');
                I('city') && $shop_where['city'] = I('city');
                // I('area') && $shop_where['area'] = I('area');
                $shop_where['status'] = '1';
                $shops = M('shop')->where($shop_where)->select();
                $shop_ids = [];
                $shop_distance_arr = [];
                if($shops){
                    if($lng && $lat){
                        $amap_key = 'd7cdde040024dc1fe22157970ba6bd6b';
                        $origins = '';
                        foreach ($shops as $key => $row) {
                            $origins.= ($origins ? "|":'').$row['lng'].','.$row['lat'];
                        }
                        $url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$origins}&coordsys=baidu";
                        $res = curl_get($url);
                        $res = json_decode($res, true);
                        $origins = '';
                        if($res['status'] == '1'){
                            $locations = $res['locations'];
                            foreach (explode(';', $locations) as $key => $row) {
                                $origins.= ($origins ? "|":'').explode(',', $row)[0].','.explode(',', $row)[1];
                            }
                        }
                        $url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$lng},{$lat}&coordsys=gps";
                        $res = curl_get($url);
                        $res = json_decode($res, true);
                        if($res['status'] == '1'){
                            $lng = explode(',', $res['locations'])[0];
                            $lat = explode(',', $res['locations'])[1];
                        }
                        try{
                            require_once 'ThinkPHP/Library/Vendor/autoload.php';
                            $res = \yishuixm\lbs\LbsAmap::distance($amap_key, $origins, $lng.','.$lat, 1);
                            $res = json_decode($res, true);
                            if($res['status'] == 1){
                                foreach ($shops as $key => &$row) {
                                    if(isset($res['results'][$key])){
                                        $row['ju'] = $res['results'][$key]['distance'];
                                        // if($row['ju'] < 10000){
                                            $shop_distance_arr[$row['id']] = $row['ju'];
                                        // }
                                    }
                                }
                            }
                        }catch(\Exception $e){

                        }
                    }
                    $shop_ids = array_column($shops, 'id');
                }
                if($shop_ids){
                    if(!isset($where['sc.shop_id'])){
                        $where['sc.shop_id'] = ['in', $shop_ids];
                    }
                }
                $list = M('ShopCof')->alias('sc')
                ->join('__SHOP__ s ON sc.shop_id=s.id', 'left')
                ->join('__USER__ u ON sc.user_id=u.id', 'left')
                ->where($where)
                ->order($order)
                ->field('sc.*,u.nickname,u.img as avatar,s.shopname')
                ->select();
                foreach ($list as $key => &$row) {
                    $row['ju'] = isset($shop_distance_arr[$row['shop_id']]) ? $shop_distance_arr[$row['shop_id']] : 9999999999;
                }
                $list = $this->array_sort($list, 'ju');
                $count = count($list);
                $start = ($page-1)*$size;//偏移量，当前页-1乘以每页显示条数
                if($count > $start){
                    $length = $count - $start;
                    $length = $length > $size ? $size : $length;
                    $list = array_slice($list, $start, $length);
                }else{
                    $list = [];
                }
                break;
            case '4':// 关注
                $shop_ids = M('shop_cof_follow')->where(['user_id'=>$this->uid])->getField('id,shop_id');
                if($shop_ids){
                    if(!isset($where['sc.shop_id'])){
                        $where['sc.shop_id'] = ['in', $shop_ids];
                    }
                    $list = M('ShopCof')->alias('sc')
                    ->join('__SHOP__ s ON sc.shop_id=s.id', 'left')
                    ->join('__USER__ u ON sc.user_id=u.id', 'left')
                    ->where($where)
                    ->where($where)
                    ->order($order)
                    ->page($page, $size)
                    ->field('sc.*,u.nickname,u.img as avatar,s.shopname')
                    ->select();
                }
                break;
            default:
                break;
        }
        if($list){
            $cof_ids = array_column($list, 'id');
            $shop_ids = array_column($list, 'shop_id');
            if($this->uid && $cof_ids){
                $like_ids = M('shop_cof_like')->where(['user_id'=>$this->uid, 'cof_id'=>['in', $cof_ids]])->getField('id,cof_id');
            }else{
                $like_ids = [];
            }
            if($this->uid && $shop_ids){
                $follow_ids = M('shop_cof_follow')->where(['user_id'=>$this->uid, 'shop_id'=>['in', $shop_ids]])->getField('id,shop_id');
            }else{
                $follow_ids = [];
            }
            $siteurl = C("SiteUrl");
            require_once 'ThinkPHP/Library/Vendor/autoload.php';
            $ffmpeg = new \Common\Util\FFMpeg();
            $ffmpeg = $ffmpeg->ffmpeg;
            $cover_path = './'.C('UPLOAD_PATH').'/videocover/';
            if(!is_dir($cover_path)){
                mkdir($cover_path, 0755, true);
            }
            foreach ($list as $key => &$row) {
                $row['read_num'] = $row['like_num']*69;
                $row['imgs'] = $row['imgs'] ? explode(',', $row['imgs']) : [];
                if($this->uid){
                    $row['is_like'] = in_array($row['id'], $like_ids) ? 1 : 0;
                }else{
                    $row['is_like'] = 0;
                }
                if($this->uid){
                    $row['is_follow'] = in_array($row['shop_id'], $follow_ids) ? 1 : 0;
                }else{
                    $row['is_follow'] = 0;
                }
                $video_cover = '';
                if($row['video']){
                    try {
                        // 视频路径
                        $video_path = str_replace($siteurl, './', $row['video']);
                        if(!is_file($video_path)){
                            $video_path = str_replace('http://www.yuzhuli.com/', './', $row['video']);
                        }
                        if(is_file($video_path)){
                            $poster_path = $cover_path.md5($video_path).'.jpg';// 生成封面保存路径
                            if(!is_file($poster_path)){
                                $video = $ffmpeg->open($video_path);
                                $frame = $video->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(1));
                                $frame->save($poster_path, false);  
                            }
                            $video_cover = str_replace('/./', '/', $siteurl.$poster_path);
                        }
                    } catch (\Exception $e) {
                        trace('生成图片失败:'.$e->getMessage(), 'error');
                    }
                }
                $row['video_cover'] = $video_cover;
            }
        }
        $is_self = 0;
        if($shop_id){
            $shop = M('shop')->where(['id'=>$shop_id])->find();
            if($shop){
                if(($this->uid && $shop['uid'] == $this->uid) || ($this->user && ($shop['phone'] == $this->user['phone'] || $shop['tel'] == $this->user['phone']))){
                    $is_self = 1;
                }
            }
        }
        $this->ajaxReturn(['s' => true, 'd' => $list, 'is_self'=>$is_self]);
    }

    public function myreleased()
    {
        $list = M('ShopCof')->alias('c')
        ->join("__SHOP__ s On c.shop_id=s.id", 'left')
        ->where(['s.uid|s.phone|tel'=>[$this->uid, $this->user['phone'], $this->user['phone'], '_multi'=>true]])
        ->order('id desc')
        ->field('c.id,c.desc,c.imgs,c.video,c.like_num,c.msg_num,c.read_num')
        ->select();
        if($list){
            foreach ($list as $key => &$row) {
                $row['imgs'] = explode(',', $row['imgs']);
            }
        }
        $this->ajaxReturn(['s' => true, 'd' => $list]);
    }

    public function add()
    {
        $post = I('post.');
        $img_is_base64 = I('img_is_base64', 1);
        $shop = M('shop')->where(['uid|phone|tel'=>[$this->uid, $this->user['phone'], $this->user['phone'], '_multi'=>true], 'status'=>1])->find();
        if(empty($shop)){
            $this->ajaxReturn(['s' => false, 'm' => '您还不是商家。']);
        }
        if(empty($post['desc']) && empty($post['imgs']) && empty($post['video'])){
            $this->ajaxReturn(['s' => false, 'm' => '请上传内容']);

        }
        if(isset($post['imgs']) && $post['imgs']){
            if($img_is_base64){
                $post['imgs'] = $this->uploadimgsy('imgs');
            }
        }

        // if(isset($_FILES['video'])){
        //     $videoInfo = uploadVideo($_FILES['video'], 1, 60);
        //     if(!$videoInfo['status']){
        //         $this->ajaxReturn(['s'=>false, 'm'=>$videoInfo['msg']]);
        //     }
        //     $post['video'] = C("SiteUrl").$videoInfo['info']['path'];
        // }
        $post['user_id'] = $this->uid;
        $post['shop_id'] = $shop['id'];
        $post['status'] = 1;
        $post['create_time'] = time();
        $post['update_time'] = time();
        $res = M('ShopCof')->add($post);
        if(!$res){
            $this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'提交成功']);
    }

    public function uploadvideo()
    {
        $videoB64 = I('video');
        if(empty($videoB64)){
            $this->ajaxReturn(['s'=>false, 'm'=>'请上传文件']);
        }
        $videoB64Arr = explode(',', $videoB64);
        $video = $videoB64Arr[1];
        $file_name = 'php'.date('YmdHis').rand(10000, 99999).'.mp4';
        $tmp_name = sys_get_temp_dir().'/'.$file_name;
        if(file_put_contents($tmp_name, base64_decode($video))){
            $file = [];
            $file['tmp_name'] = $tmp_name;

            // if(empty($_FILES)){
            //     $this->ajaxReturn(['s'=>false, 'm'=>'请上传文件']);
            // }
            // $file = reset($_FILES);

            $videoInfo = uploadVideo($file, 1, 20);
            if(!$videoInfo['status']){
                $this->ajaxReturn(['s'=>false, 'm'=>$videoInfo['msg']]);
            }
            $video = C("SiteUrl").$videoInfo['info']['path'];
            $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'video'=>$video]);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'上传失败']);
        }
    }

    public function segmentupload()
    {
        (new UploadController())->segmentvideo();
    }

    /**
     * 点赞
     */
    public function like()
    {
        $cof_id = I('cof_id');
        $has = M('shop_cof_like')->where(['cof_id'=>$cof_id, 'user_id'=>$this->uid])->find();
        if($has){
            $this->ajaxReturn(['s' => false, 'm' => '您已点赞']);
        }
        $confInfo = M('shop_cof')->where(['id'=>$cof_id])->find();
        if(empty($confInfo)){
            $this->ajaxReturn(['s' => false, 'm' => '信息不存在或已被删除，无法点赞。']);
        }
        M('shop_cof_like')->add([
            'cof_id'        => $cof_id,
            'user_id'       => $this->uid,
            'create_time'   => time(),
        ]);
        M('shop_cof')->where(['id'=>$cof_id])->setInc('like_num', 1);
        // M('shop_cof')->where(['id'=>$cof_id])->setInc('read_num', 69);
        $this->ajaxReturn(['s' => true, 'm' => 'ok']);
    }

    /**
     * 留言列表
     */
    public function leave_msg_list()
    {
        $cof_id = I('cof_id');
        $page = I('page', 1);
        $size = I('size', 20);
        $list = [];
        $list = M('shop_cof_leave_msg')->alias('l')
        ->join('__USER__ u ON l.user_id=u.id', 'left')
        ->where(['l.cof_id'=>$cof_id])
        ->page($page, $size)
        ->order('l.create_time desc')
        ->field('u.nickname,u.img,l.content,l.create_time as time')
        ->select();
        if($list){
            foreach ($list as $key => &$row) {
                $row['time'] = date('Y-m-d H:i:s', $row['time']);
            }
        }
        $this->ajaxReturn(['s' => true, 'd' => $list]);
    }

    /**
     * 留言
     */
    public function leave_msg()
    {
        $cof_id = I('cof_id');
        $content = trim(I('content'));
        if(empty($content)){
            $this->ajaxReturn(['s' => false, 'm' => '请输入留言内容']);
        }
        $cofInfo = M('ShopCof')->where(['id'=>$cof_id])->find();
        if(empty($cofInfo)){
            $this->ajaxReturn(['s' => false, 'm' => '内容不存在或已删除，无法留言。']);   
        }
        $res = M('shop_cof_leave_msg')->add([
            'cof_id'    => $cof_id,
            'user_id'   => $this->uid,
            'content'   => $content,
            'create_time'   => time(),
            'update_time'   => time(),
        ]);
        M('shop_cof')->where(['id'=>$cof_id])->setInc('msg_num', 1);
        $this->ajaxReturn(['s' => true, 'm' => 'ok']);
    }

    /**
     * 关注
     */
    public function follow()
    {
        $shop_id = I('shop_id');
        $shopInfo = M('shop')->where(['id'=>$shop_id])->find();
        if(empty($shopInfo) || $shopInfo['status']!=1){
            $this->ajaxReturn(['s'=>false, 'm'=>'商家不存在或已关闭']);
        }
        $info = M('shop_cof_follow')->where(['shop_id'=>$shop_id, 'user_id'=>$this->uid])->find();
        if($info){
            $this->ajaxReturn(['s'=>false, 'm'=>'您已关注']);
        }
        $res = M('shop_cof_follow')->add([
            'shop_id'       => $shop_id,
            'user_id'       => $this->uid,
            'create_time'   => time(),
        ]);
        $this->ajaxReturn(['s'=>true, 'm'=>'关注成功']);
    }

    /**
     * 取关
     */
    public function unfollow()
    {
        $shop_id = I('shop_id');
        $info = M('shop_cof_follow')->where(['shop_id'=>$shop_id, 'user_id'=>$this->uid])->find();
        if(empty($info)){
            $this->ajaxReturn(['s'=>false, 'm'=>'您未关注该商家']);
        }
        M('shop_cof_follow')->where(['shop_id'=>$shop_id, 'user_id'=>$this->uid])->delete();
        $this->ajaxReturn(['s'=>true, 'm'=>'取关成功']);
    }

    public function delete()
    {
        $cof_id = I('cof_id');
        if(empty($cof_id)){
            $this->ajaxReturn(['s'=>false, 'm'=>'参数错误']);
        }
        $shopCof = M('shop_cof')->where(['id'=>$cof_id])->find();
        if(empty($shopCof)){
            $this->ajaxReturn(['s'=>false, 'm'=>'不存在或已删除']);
        }
        if($shopCof['user_id']!=$this->uid){
            $this->ajaxReturn(['s'=>false, 'm'=>'非法删除操作']);
        }
        M('shop_cof')->where(['id'=>$cof_id])->delete();
        $this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
    }
}